package com.yuanfeng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.GoodsInfoDTO;
import com.yuanfeng.base.dto.QuCommonsParamDTO;
import com.yuanfeng.base.dto.SubmitAuditCommonsDTO;
import com.yuanfeng.base.dto.SubmitAuditGoodsDTO;
import com.yuanfeng.base.entity.BaseWxLiveGoodsEntity;
import com.yuanfeng.base.mapper.BaseWxLiveGoodsMapper;
import com.yuanfeng.base.service.BaseWxLiveGoodsService;
import com.yuanfeng.base.utils.AccessTokenUtil;
import com.yuanfeng.base.vo.DelWxSubmitGoodsVO;
import com.yuanfeng.base.vo.WxSubmitGoodsVO;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.wx.HttpUtlis;
import com.yuanfeng.commoms.util.wx.NewWxMaterialResult;
import com.yuanfeng.commoms.util.wx.UploadWxUtil;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class BaseWxLiveGoodsServiceImpl extends ServiceImpl<BaseWxLiveGoodsMapper, BaseWxLiveGoodsEntity>
    implements BaseWxLiveGoodsService{

    @Autowired
    private RestTemplate restTemplate;

    @Value("${fontUrlPath}")
    private String urlPath;


    @Override
    public ResponseResult upAuditCommons(Map<String, Object> param) {

        String token = param.get("token").toString();
        String path = "https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token=";

        BaseWxLiveGoodsEntity wxLiveGoods =this.baseMapper.selectById(param.get("id").toString());

        Map<String, Integer> map = new HashMap<>();
        if (null != wxLiveGoods) {
            map.put("goodsId", wxLiveGoods.getWxGoodsId());
        }
        String accessToken = AccessTokenUtil.queryAccessToken();
        path = path + accessToken;
        DelWxSubmitGoodsVO result = restTemplate.postForObject(path, map, DelWxSubmitGoodsVO.class);
        if (result.getErrcode() == 0) {
            Integer integer = this.baseMapper.deleteById(param.get("id").toString());
            if (integer > 0) {
               return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
            }
        } else if (result.getErrcode() == 300015) {
            return ResponseResult.success(BizCodeEnume.GOODS_NOT_EXIST);
        } else {
            return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult queryLiveCommons(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(token);
        if (null != userInfo) {
            param.put("shopId",userInfo.getShopId());
        }else{
            param.put("shopId",null);
        }

        IPage<BaseWxLiveGoodsEntity> page=this.baseMapper.queryLiveCommons(new Query<BaseWxLiveGoodsEntity>().getPage(param),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult delLiveCommons(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        List<Integer> commonIds = (List<Integer>) param.get("commonIds");
        List<Integer> ids = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (Integer commonId : commonIds) {
            QueryWrapper<BaseWxLiveGoodsEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("common_id",commonId);
            BaseWxLiveGoodsEntity wxLiveGoods = this.baseMapper.selectOne(queryWrapper);
            if(null != wxLiveGoods) {
                if (1 != wxLiveGoods.getIsverify()) {
                    ids.add(wxLiveGoods.getId());
                } else {
                    map.put("id",wxLiveGoods.getId());
                    this.upAuditCommons(map);
                }
            }
        }
        Integer integer = this.baseMapper.deleteBatchIds(ids);
        if (integer > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(2, "操作失败");
    }

    @Override
    public ResponseResult addLiveCommons(QuCommonsParamDTO param) {
        String token = param.getToken();
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }

        Integer[] commonIds=param.getCommonIds();
        List<BaseWxLiveGoodsEntity> wxLiveGoodsList = new ArrayList<>();
        for (Integer commonId : commonIds) {
            BaseWxLiveGoodsEntity wxLiveGoods = this.baseMapper.queryCommonDetail(commonId);
            wxLiveGoods.setOperation(1);
            wxLiveGoods.setIsverify(4);
            wxLiveGoodsList.add(wxLiveGoods);
        }
        Integer integer = this.baseMapper.insertLiveGoods(wxLiveGoodsList);
        if (integer > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(2, "操作失败");
    }

    @Override
    public ResponseResult submitAuditCommons(SubmitAuditCommonsDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            String path = YFConfig.WX_LIVE_GOODS;
            if (param.getIsverify().equals(CommonType.liveGoodsVerify.AUDIT_ERROR.getCode())) {
                Integer integer = this.baseMapper.update(null,new LambdaUpdateWrapper<BaseWxLiveGoodsEntity>()
                                                 .eq(BaseWxLiveGoodsEntity::getId,param.getId())
                                                 .set(BaseWxLiveGoodsEntity::getCause,param.getCause())
                                                 .set(BaseWxLiveGoodsEntity::getIsverify, CommonType.liveGoodsVerify.AUDIT_ERROR.getCode())
                                                 .set(BaseWxLiveGoodsEntity::getOperation,CommonType.commonStatus.NO.getCode()));
                if (integer > 0) {
                    return ResponseResult.success();
                }
            }
            BaseWxLiveGoodsEntity wxLiveGoods = this.baseMapper.selectById(param.getId());
            if (wxLiveGoods.getCommonName().length() > 14) {
                wxLiveGoods.setCommonName(wxLiveGoods.getCommonName().substring(0, 13));
            }
            SubmitAuditGoodsDTO goodsParam = new SubmitAuditGoodsDTO();
            GoodsInfoDTO goodsInfo = new GoodsInfoDTO();
            if (null != wxLiveGoods) {
                String accessToken = AccessTokenUtil.queryAccessToken();
                path = path + accessToken;
                //获取商品图片
                System.out.println(path);
                String commonImage = wxLiveGoods.getCommonImage();
                HttpUtlis httpUtlis = new HttpUtlis();
                Map<String, String> stringStringMap = httpUtlis.doGetImages(commonImage, 1, urlPath);
                if (null != stringStringMap.get("integer") && "false".equals(stringStringMap.get("integer"))) {
                    return ResponseResult.fail(BizCodeEnume.WX_LIVE_HOST_12);
                }
                System.out.println(stringStringMap.get("pathName"));
                NewWxMaterialResult materialResult = null;
                try {
                    materialResult = UploadWxUtil.uploadFile(stringStringMap.get("pathName"), accessToken);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                goodsInfo.setCoverImgUrl(materialResult.getMediaId());
                goodsInfo.setName(wxLiveGoods.getCommonName());
                goodsInfo.setPriceType(1);
                goodsInfo.setPrice(wxLiveGoods.getGoodsPrice());
                goodsInfo.setUrl("pages/description/descrption?goodsId=" + wxLiveGoods.getGoodsId() + "&commonId=" + wxLiveGoods.getCommonId() + "");
                goodsParam.setGoodsInfo(goodsInfo);
                WxSubmitGoodsVO result = restTemplate.postForObject(path, goodsParam, WxSubmitGoodsVO.class);
                if (result.getErrcode() == 0) {
                    Integer integer =  this.baseMapper.update(null,new LambdaUpdateWrapper<BaseWxLiveGoodsEntity>()
                                   .eq(BaseWxLiveGoodsEntity::getId,param.getId())
                                   .set(BaseWxLiveGoodsEntity::getWxGoodsId,result.getGoodsId())
                                   .set(BaseWxLiveGoodsEntity::getCause,CommonType.liveGoodsVerify.WAIT_WX_AUDIT.getDesc())
                                   .set(BaseWxLiveGoodsEntity::getIsverify, CommonType.liveGoodsVerify.WAIT_WX_AUDIT.getCode())
                                   .set(BaseWxLiveGoodsEntity::getOperation,CommonType.commonStatus.NO.getCode()));
                    if (integer > 0) {
                        return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);
                    }
                }
            }
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }
}




